const Service = require('egg').Service
const OSS = require('ali-oss');
const fs = require('fs');
const path = require('path');
module.exports = class CommonService extends Service {
  /**
   * 查询一条数据
   * sql
   */
  async findOne({
    tableName = '',
    where = {},
    filed = [],
    others = '',
    sql,
    model = 'model'
  }) {
    let {
      ctx,
      logger,
    } = this
    let sqlFormData = ctx.helper.sqlFormData
    try {
      // let _where = where?
      // model = model || 'model'
      if (!sql) {
        sql = `
          SELECT ${filed.join(',') || '*'}
          FROM ${tableName}
          ${where ? sqlFormData(where, 'where') : ''}
          ${others}
        `
        // sql = where ? ` ${sql} WHERE ${sqlFormData(where, 'where')}` : sql
      }
      let res = await ctx[model].query(sql, {
        type: 'SELECT'
      })
      return res[0]
    } catch (error) {

      logger.info(`findOne查询报错`)
      return null
    }
  }

  async findAll(param) {
    const {
      ctx,
      logger
    } = this, sqlFormData = ctx.helper.sqlFormData;
    let { tableName = '', where = {}, others = '', filed = [], model = 'model', sql } = param;
    // model = model || 'model';
    // console.log('%c gc_param=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', param);
    try {
      // let sql = ''
      console.log('xxxxjjjjjj', sqlFormData(where, 'where'))
      if (!sql) {
        sql = `
        SELECT ${filed.join(',') || '*'}
        FROM ${tableName}
        ${where ? sqlFormData(where, 'where') : ''}
        ${others}
      `
      }
      let res = await ctx[model].query(sql, {
        type: 'SELECT'
      })
      return res
    } catch (error) {

      logger.info(`findAll查询报错`)
      logger.error(`${error}`);
      return null
    }
  }

  /**
   * 给数据库中插入一条数据
   * @param {*} tableName  表名
   * @param {*} params     参数
   */
  async insertOne({
    tableName,
    params,
    model = 'model'
  }) {
    let { ctx, app, logger } = this
    let res = await ctx[model].query(`
      INSERT INTO ${tableName} (${Object.keys(params).join(',')}) VALUES (${Object.values(params)})
      `)
    return res
  }

  /**
   * 表名
   * @param {*} tableName
   * @param {*} value
   * @param {*} where
   */
  async upData({ tableName, value, where, model = 'model' }) {
    let {
      ctx,
      app,
      logger
    } = this
    // try {
    // let _value = [];
    // let _where = [];
    let sql = ''
    if (!value instanceof Object) {
      return false
    }
    let sqlFormData = ctx.helper.sqlFormData
    sql = `UPDATE ${tableName}
    ${sqlFormData(value, 'SET')}
    ${sqlFormData(where, 'where')}
    `;
    // if (where instanceof Object) {
    //   sql = `${sql} WHERE ${sqlFormData(where, 'where')}`
    // }

    await ctx[model].query(sql);
    return true
    // } catch (error) {
    //   console.log(error)
    //   logger.info(`更新失败=>${JSON.stringify(value)}`);
    //   logger.error(`${error}`)
    //   return false
    // }

  }

  /**
   * 表名
   * @param {*} tableName
   * @param {*} value
   * @param {*} where
   */
  async del({ tableName, where, model = 'model' }) {
    let {
      ctx,
      app,
      logger
    } = this
    // try {
    // let _value = [];
    // let _where = [];
    let sql = ''
    let sqlFormData = ctx.helper.sqlFormData
    sql = `DELETE
     FROM ${tableName}
    ${sqlFormData(where, 'where')}
    `;
    await ctx[model].query(sql);
    return true
  }


  /**
   * 根据活动id从redis中获取活动信息
   * @param {*} activityId  活动id
   * @param {*} level       奖品级别
   *
   */
  async redisActiveInfo(activityId, level) {
    let {
      app,
      config,
      ctx,
      logger
    } = this;
    let rule = '';
    // let activeInfo = {};
    try {
      let activeKey = `${config.redisKey.activeBaseInfo}:${activityId}`;
      let rulesKey = `${config.redisKey.prizeRules}:${activityId}`
      let activeInfo = await app.redis.hgetall(activeKey);
      let rules = JSON.parse(await app.redis.hget(rulesKey, 'nonstandardActivityAward'));
      //
      rules.some((item) => {
        if (item.condition.level == level) {
          rule = item.result.getReward
          return true
        }
      })

      return {
        activeInfo,
        rule
      }
    } catch (error) {

      logger.error(`读取活动信息报错${error}`)
      return {
        activeInfo: '',
        rule
      }
    }
  }
  /**
   *
   * @param {*} userId  用户id
   * @param {*} type    查询类型 (是否需要返回手机号，银行卡等信息)
   */
  async getUserInfo(userId, type) {
    let {
      ctx,
      logger
    } = this;
    try {
      let userData = (await ctx.appModel.query(`
        SELECT
          USER .userid,
          USER .username,
          USER .mobile,
          tr.region_name as province_name
        FROM
          tb_user AS USER
        LEFT JOIN tb_region AS tr ON USER .regionid = tr.regionid
        WHERE
          USER .userid = ${userId}
        `, {
          type: 'SELECT'
        }))[0];
      return userData
    } catch (error) {
      logger.info(`查询用户信息失败===>${error}`)
      return null
    }

  }

  /**
   *
   */
  async upLoad() {
    const { ctx, logger, service, app } = this;
    let client = new OSS(app.config.oss);
    const stream = await ctx.getFileStream();
    let { dir } = stream.fields;
    // console.log()
    // let origin = ctx.request.header.origin
    console.log('%c gc_dir=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', dir);
    if (!dir) {
      return {
        code: 10201,
        msg: "dir不能为空！"
      }
    }
    const filename = `${Math.random().toString(36).substr(2)}${new Date().getTime()}${path.extname(stream.filename).toLocaleLowerCase()}`;
    // 拼接图片存放路径
    let _path = `upLoad/img/${dir}/${filename}`;
    try {
      let result = await client.putStream(_path, stream);
      // console.log(result, '-----------result---result')
      let { name, url } = result
      return {
        code: 10200,
        data: {
          url,
        },
        msg: 'success'
      }

    } catch (err) {
      return {
        code: 10500,
        msg: "上传失败"
      }
    }
    return {
      code: 1000,
      msg: 'success'
    }
  }

}